package com.sky.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.po.*;
import com.sky.repository.OrderDetailRepository;
import com.sky.repository.OrderRepository;
import com.sky.repository.UserRepository;
import com.sky.result.PageResult;
import com.sky.service.AddressBookService;
import com.sky.service.OrderDetailService;
import com.sky.service.OrderService;
import com.sky.service.ShoppingCartService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.aspectj.bridge.Message;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Content:
 * @Author: Asen
 * @Date: 2023/9/11 15:38
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    @Lazy
    private AddressBookService addressBookService;
    @Autowired
    @Lazy
    private ShoppingCartService shoppingCartService;
    @Autowired
    @Lazy
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;
    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     * @param source
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO source) {
        //处理各种业务异常:地址簿为空,
        AddressBookPO addressBookPO = addressBookService.getById(source.getAddressBookId());
        if(ObjUtil.isNull(addressBookPO)){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户收获地址是否超出配送范围
        checkOUtOfRange(addressBookPO.getCityName()+addressBookPO.getDistrictName()+addressBookPO.getDetail());
        //购物车为空
        //查询当前用户购物车信息
        List<ShoppingCartPO> shoppingCartPOS = shoppingCartService.list();
        if (CollUtil.isEmpty(shoppingCartPOS)){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //向订单表插入数据
        OrdersPO ordersPO = OrderMapper.INSTANCE.DTOConvertPO(source);
        ordersPO.setOrderTime(LocalDateTime.now());
        ordersPO.setPayStatus(OrdersPO.UN_PAID);
        ordersPO.setStatus(OrdersPO.PENDING_PAYMENT);
        ordersPO.setNumber(String.valueOf(IdWorker.getId()));
        ordersPO.setPhone(addressBookPO.getPhone());
        ordersPO.setConsignee(addressBookPO.getConsignee());
        ordersPO.setAddress(addressBookPO.getProvinceName()+addressBookPO.getDistrictName()+addressBookPO.getDetail());
        ordersPO.setUserId(addressBookPO.getUserId());
        orderRepository.insert(ordersPO);
        //向订单明细表插入数据
        List<OrderDetailPO> orderDetailPOS = ShoppingCartMapper.INSTANCE.ListPOConvertDetail(shoppingCartPOS);
        orderDetailPOS.forEach(s->{
            s.setOrderId(ordersPO.getId());
        });
        orderDetailService.insertBatch(orderDetailPOS);
        //清空当前用户的购物车数据
        shoppingCartService.clean();
        //返回结果
        OrderSubmitVO orderSubmitVO = new OrderSubmitVO(ordersPO.getId(),
                ordersPO.getNumber(),
                ordersPO.getAmount(),
                ordersPO.getOrderTime());
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        UserPO user = userRepository.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        OrdersPO ordersDB = orderRepository.selectById(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        OrdersPO orders = new OrdersPO();
                orders.setId(ordersDB.getId());
                orders.setStatus(OrdersPO.TO_BE_CONFIRMED);
                orders.setPayStatus(OrdersPO.PAID);
                orders.setCheckoutTime(LocalDateTime.now());

//        orderRepository.updateById(orders);

    }

    /**
     * 订单搜索
     * @param source
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO source) {
        final String[] dishName = {""};
        Page<OrderVO> page = new Page<>(source.getPage(),source.getPageSize());
        orderRepository.conditionSearch(page,source);
        page.getRecords().forEach(s->{
            s.getOrderDetailPOList().forEach(d->{
                dishName[0] += d.getName() +"*"+d.getNumber() +";";
            });
            s.setOrderDishes(dishName[0]);
        });
        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 各个订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed((int)orderRepository.selectList(new LambdaQueryWrapper<OrdersPO>()
                .eq(OrdersPO::getPayStatus, OrdersPO.CONFIRMED)).stream().count());
        orderStatisticsVO.setToBeConfirmed((int)orderRepository.selectList(new LambdaQueryWrapper<OrdersPO>()
                .eq(OrdersPO::getPayStatus,OrdersPO.TO_BE_CONFIRMED)).stream().count());
        orderStatisticsVO.setDeliveryInProgress((int)orderRepository.selectList(new LambdaQueryWrapper<OrdersPO>()
                .eq(OrdersPO::getPayStatus, OrdersPO.DELIVERY_IN_PROGRESS)).stream().count());
        return orderStatisticsVO;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO detail(Long id) {
        return orderRepository.detail(id);
    }

    /**
     * 接单
     * @param source
     */
    @Override
    public void confirm(OrdersConfirmDTO source) {
        OrdersPO ordersPO = orderRepository.selectById(source.getId());
        ordersPO.setStatus(OrdersPO.CONFIRMED);
        orderRepository.updateById(ordersPO);
    }

    /**
     * 拒单
     * @param source
     */
    @Override
    public void rejection(OrdersRejectionDTO source) {
        OrdersPO ordersPO = orderRepository.selectById(source.getId());
        //订单只有存在且状态为2(待接单)才可以拒单
        if(ObjUtil.isNull(ordersPO) || !ordersPO.getStatus().equals(OrdersPO.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //退款
        //拒单
        ordersPO.setStatus(OrdersPO.CANCELLED);
        ordersPO.setRejectionReason(source.getRejectionReason());
        ordersPO.setCancelReason(source.getRejectionReason());
        ordersPO.setCancelTime(LocalDateTime.now());
        orderRepository.updateById(ordersPO);
    }

    /**
     *
     * @param source
     */
    @Override
    public void cancel(OrdersCancelDTO source) {
        OrdersPO ordersPO = orderRepository.selectById(source.getId());
        ordersPO.setStatus(OrdersPO.CANCELLED);
        ordersPO.setCancelReason(source.getCancelReason());
        ordersPO.setCancelTime(LocalDateTime.now());
        orderRepository.updateById(ordersPO);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        OrdersPO ordersPO = orderRepository.selectById(id);
        //检验订单是否存在并且状态为3
        if (ObjUtil.isNull(ordersPO) || !ordersPO.getStatus().equals(OrdersPO.CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态,转为派送中
        ordersPO.setStatus(OrdersPO.DELIVERY_IN_PROGRESS);
        orderRepository.updateById(ordersPO);
    }

    @Override
    public void complete(Long id) {
        OrdersPO ordersPO = orderRepository.selectById(id);
        //检查订单是否存在并且状态为4
        if (ObjUtil.isNull(ordersPO) || !ordersPO.getStatus().equals(OrdersPO.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //更新订单状态,转为已完成
        ordersPO.setStatus(OrdersPO.COMPLETED);
        ordersPO.setDeliveryTime(LocalDateTime.now());
        orderRepository.updateById(ordersPO);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //查询当前用户id
        Long currentId = BaseContext.getCurrentId();
        //根据订单查询当前订单详情
        List<OrderDetailPO> orderDetailPOS = orderDetailRepository.selectList(new LambdaQueryWrapper<OrderDetailPO>()
                .eq(OrderDetailPO::getOrderId, id));
        //将订单详情对象转换为购物车对象
        List<ShoppingCartPO> source = orderDetailPOS.stream().map(x->{
            ShoppingCartPO shoppingCart = new ShoppingCartPO();
            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(currentId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将购物车对象批量添加到数据库
        shoppingCartService.saveShoppingCart(source);
    }

    /**
     * 客户催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        OrdersPO ordersPO = orderRepository.selectById(id);
        //检查订单
        if (ObjUtil.isNull(ordersPO)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //通过websocket向客户端浏览器推送消息
        Map map = new HashMap();
        map.put("type",1);//1:来单提醒,2:客户催单
        map.put("orderId",ordersPO.getId());
        map.put("content","订单号"+ordersPO.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
    }

    /**
     * 检查客户收货地址是否超出范围
     * @param address
     */
    private void checkOUtOfRange(String address){
        Map map = new HashMap<>();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);
        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3",map);
        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }
        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        map.put("address",address);
        //获取用户收获地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3",map);
        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }
        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }
}
